package com.qm.service.impl;

import com.qm.service.FileService;
import com.qm.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 @author james
 @create 2021-03-23 16:50
 */
@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService {

    @Value("${image.localDirPath}")
    private String localDirPath;
    @Value("${image.urlPath}")
    private String urlPath;

    /**
     * 文件上传策略:
     *      1.图片类型的校验    1.正则表达式.. 2.???
     *      2.校验文件是否为木马   木马.exe.jpg 宽度/高度
     *      3.将文件分目录存储    1.hash asdfsdfa 2.时间
     *      4.防止文件重名  uuid当做名称
     * @param uploadFile
     * @return ImageVO
     */
    @Override
    public ImageVO uploadFile(MultipartFile uploadFile) {
        //1.图片类型校验
        String fileName = uploadFile.getOriginalFilename();
        fileName = fileName.toLowerCase();
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")) {
            return ImageVO.fail();
        }
        //2.是否为恶意程序
        try {
            BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            if(height == 0 || width ==0) {
                //说明该文件是一个恶意程序
                return ImageVO.fail();
            }
            //3.根据时间动态生成文件目录
            String dateDirPath =
                    new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String localDir = localDirPath + dateDirPath;
            File dirFile = new File(localDir);
            if(!dirFile.exists()) {
                dirFile.mkdirs();   //mkdirs()创建多级目录
            }
            //4.动态生成用户名称
            String uuid = UUID.randomUUID().toString().replace("-","");
            int index = fileName.lastIndexOf(".");
            String fileType = fileName.substring(index);
            String realFileName = uuid + fileType;

            //5.实现文件上传 文件目录/文件名称
            File imageFile = new File(localDir + realFileName);
            uploadFile.transferTo(imageFile);

            //6.虚拟路径的拼接
            String url = urlPath + dateDirPath + realFileName;
            return ImageVO.success(url, width, height);
        } catch (IOException e) {
            e.printStackTrace();
            return ImageVO.fail();
        }
    }
}
